#include <lang/Java.h>

#include <lang/java/jni.h>

namespace multilang {

#define MLANG_JAVA_VERSION JNI_VERSION_1_8

JavaVM* Java::jvm = NULL;

bool Java::init(){
    JavaVMInitArgs args;
    JavaVMOption options[3]{};
    JNIEnv* env;

    if (jvm)
        return false;

    options[0].optionString = const_cast<char*>("-Djava.class.path=./build/java");
    options[1].optionString = const_cast<char*>("-Djava.compiler=NONE");
    options[2].optionString = const_cast<char*>("-verbose:NONE");

    args.version = MLANG_JAVA_VERSION;
    args.ignoreUnrecognized = JNI_FALSE;
    args.nOptions = lengthof(options);
    args.options = options;

    if(JNI_CreateJavaVM(&jvm, (void**)&env, &args) == JNI_ERR){
        printf("JNI_CreateJavaVM Error!\n");
        return false;
    }

    return true;
}

bool Java::uninit(){
    if (!jvm)
        return false;
    
    jvm->DestroyJavaVM();
    jvm = NULL;
    return true;
}

JNIEnv* Java::attachThread(){
    JNIEnv* env;
    jvm->AttachCurrentThread((void**)&env, NULL);
    return env;
}

void Java::detachThread(){
    jvm->DetachCurrentThread();
}

JNIEnv* Java::getEnv(){
    JNIEnv* env;
    jvm->GetEnv((void**)&env, MLANG_JAVA_VERSION);
    return env;
}

}